import Http from '../../../../utils/http.js';
import { isEmpty } from '../../../../utils/util.js';
let app = getApp()
var prevPage;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading:false,
    commodityList:[],
    addrBizid:'',//收货地址bizid
    region: [],
    currentAddress: '',//收货地址
    receiveName:'',//收货人
    receivePhone: '',//收货电话
    orderState: '',
    submitWaiting: false,//订单提交中
    payWaiting:false,//支付中
    submitSucc: false,//订单提交成功
    disabled: false,//表单是否可编辑
    custRemark:'',//买家留言
    actualPayAmount:0,//实际支付
    discountAmount: 0,//折扣金额
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.setData({
      commodityList: options.commodityList && JSON.parse(options.commodityList)||[],
      disabled: !isEmpty(options.orderState),
      orderCode: options.orderCode||''
    });

    if (!isEmpty(this.data.orderCode)) {
      this.getOrderDetailByCode();
    } else {
      this.getOrderDetail();
      this.getAddrList();
    }
   
  },
  //待支付倒计时结束
  timeEnd() {
    this.setData({
      orderState: 'CANCELED'
    })
  },
  //根据订单编号查询订单详情
  getOrderDetailByCode() {
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    Http.Request('GET', `/api/customer/order/getOrderDetailByOrderCode/${this.data.orderCode}/v1`).then(res => {
      this.setData({
        receivePhone: res.userPhone,
        receiveName: res.name,
        currentAddress: res.receiveAddress,
        actualPayAmount: res.actualPayAmount,
        discountAmount: res.discountAmount,
        postage: res.postage,
        commodityList:res.commodity||[],
        subtotal: res.subtotal,
        preferentialAmount: res.preferentialAmount,
        remainingMills: res.remainingMills,
        commodityName: res.commodity[0].commodityName,
        commoditySellingPoint: res.commodity[0].commoditySellingPoint,
        commodityCode: res.commodity[0].commodityCode,
        commodityImage: res.commodity[0].firstImage,
        orderState: res.orderState.name,
        custRemark: res.custRemark,
        disabled: !isEmpty(res.orderState.name),
        loading: false,
        submitSucc: true
      })
      wx.hideLoading();
    })
  },
  //获取收货地址
  getAddrList(){
    Http.Request('GET', `/api/customer/receiveAddress/receiveAddress/v1`).then(res=>{
      if(res&&res.length){
        const addresInfo = res.find(o=>{
          return o.isDefaultAddress===true
        }) || res[0]
        this.setData({
          currentAddress: addresInfo.province + addresInfo.city + addresInfo.district + addresInfo.receiveAddress,
          receiveName: addresInfo.receiveName,
          receivePhone: addresInfo.receivePhone,
          addrBizid: addresInfo.bizid
        })
      }
    })
  },
  //获取订单明细
  getOrderDetail(){
    this.setData({
      loading: true
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const data = {
      commodity: this.data.commodityList
    }
    Http.Request('POST', `/api/customer/order/orderMoneyDetail/v1`, data).then(res=>{
      wx.hideLoading();
      this.setData({
        loading:false,
        actualPayAmount: res.actualPayAmount,
        discountAmount: res.discountAmount,
        postage: res.postage,
        subtotal: res.subtotal,
        preferentialAmount: res.preferentialAmount
      })
    }).catch(err=>{
      wx.hideLoading();
      app.globalFn.reLoad(this.getOrderDetail, err)
    })
  },
  bindKeyInput(e) {
    const value = e.detail.value;
    const key = e.target.dataset.key;
    this.setData({
      [key]: value
    })
  },
  //提交订单
  handleSubmit(){
    if (this.data.submitWaiting || this.data.payWaiting) return
    if (!this.data.submitSucc){//订单未提交
      //数据校验
      if (isEmpty(this.data.addrBizid)) {
        wx.showToast({
          title: '请选择收货地址',
          icon: "none",
          duration: app.globalData.duration
        })
        return
      }
      wx.showLoading({
        title: '订单提交中',
        mask: true
      })
      this.setData({
        submitWaiting: true
      })
      const data = {
        commodity: this.data.commodityList,
        custRemark: this.data.custRemark,
        name: this.data.receiveName,
        receiveAddress: this.data.currentAddress,
        userPhone: this.data.receivePhone
      }
      Http.Request('POST', `/api/customer/order/placeOrder/MATERIAL_COMMODITY/v1`, data).then(res => {
        wx.hideLoading();
        wx.showToast({
          title: '订单提交成功',
          icon: "success",
          duration: app.globalData.duration
        })
        this.setData({
          orderCode: res.orderCode,
          remainingMills: res.mills,
          orderState: res.orderState.name,
          submitWaiting: false,
          submitSucc: true
        })
        //清空对应购物车中的商品
        if (prevPage.route ==='pages/shoppingCart/shoppingCart'){
          let shoppingCartList = prevPage.data.shoppingCartList
          for (let i = 0; i < shoppingCartList.length;i++){
            const bizid = shoppingCartList[i].bizid;
            if (this.data.commodityList.some(o=>{
              return o.bizid === bizid
            })){
              this.delShoppingCart(bizid)
            }
          }
        }
      }).catch(err => {
        wx.hideLoading();
        wx.showToast({
          title: err,
          icon: "none",
          duration: app.globalData.duration
        })
        this.setData({
          submitWaiting: false,
          submitSucc: false
        })
      })
    } else{//去支付
      this.handlePay();
    }
 
  },
  //删除购物车中的商品
  delShoppingCart(bizid){
    Http.Request('DELETE', `/api/customer/shoppingCart/delete/${bizid}/v1`)
  },
  //支付
  handlePay() {
    this.setData({
      payWaiting: true
    })
    Http.Request('POST', `/api/customer/audio/pay/${this.data.orderCode}/v1`).then(res => {
      wx.requestPayment({
        'timeStamp': res.timeStamp,
        'nonceStr': res.nonceStr,
        'package': res.package,
        'signType': res.signType,
        'paySign': res.sign,
        'success': (res) => {
          wx.showToast({
            title: '支付成功',
            icon: 'success',
            duration: app.globalData.duration
          })
          this.setData({
            orderState:'PAID'
          })
        },
        complete: () => {
          this.setData({
            payWaiting: false
          })
        }
      })
    }).catch(err => {
      this.setData({
        payWaiting: false
      })
      wx.showToast({
        title: err,
        icon: 'none',
        duration: app.globalData.duration
      })
    })
  },
  //选择收货地址
  selectAddr(){
    if (this.data.submitSucc){
      wx.showToast({
        title: '你不能再修改地址了',
        icon: "none",
        duration: app.globalData.duration
      })
      return
    }
    wx.navigateTo({
      url: `../../../addressList/addressList?refer=shiwu&currentBizid=${this.data.addrBizid}`,
    })
  },
  onShow: function () {
    var pages = getCurrentPages();
    prevPage = pages[pages.length - 2];
    console.log(prevPage)
  }
})